<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changValue"
        />
        <!-- 树形组件 -->
        <!--
          ref="deptTree"  ref属性
          node-key="id"   key标识
          @current-change="selectNode"  节点事件
          :data="depts" 数据
          :props="defaultProps" 树形配置
          :expand-on-click-node="false" 关闭点击折叠展开
        default-expand-all  默认展开所有
        :highlight-current="true" 高亮
      -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <!-- 头像 -->
          <el-table-column align="center" label="头像" width="80" prop="staffPhoto">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <!-- 聘用方式 -->
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="btnRole(row.id)">角色</el-button>
              <!--  slot="reference" -->
              <el-popconfirm title="这是一段内容确定删除吗" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left: 10px;" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px;">
          <el-pagination
            small
            layout="total,prev, pager, next"
            :total="total"
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
    </div>
    <!-- excel组件 -->
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!-- 分配角色弹出层-->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          <el-button size="small" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, exportEmployee, delEmployee, getEnableroleList, assignRole, getEmployeeDetail } from '@/api/employee'
import { getDepartment } from '@/api/department'
import { transListToTresData } from '@/utils'
import ImportExcel from './components/import-excel.vue'
import FileSaver from 'file-saver'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [], // 部门树形列表
      defaultProps: {
        label: 'name', // 部门名称
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null, // 记录部门ID
        page: 1, // 当前页码
        pagesize: 10, // 当前页码条数
        keyword: '' // 根据名字模糊查询
      },
      total: 0, // 总数
      list: [], // 获取员工数据
      roleIds: [], // 绑定数据
      roleList: [], // 可用角色列表
      showExcelDialog: false, // excel弹层
      showRoleDialog: false, // 角色弹层
      currentUserId: null // 用来记录当前点击的用户id
    }
  },

  created() {
    this.getDepartment()
    this.getEmployeeList()
  },
  methods: {
    // 分配角色
    async btnRole(id) {
      // 展示所有可用的角色列表
      this.roleList = await getEnableroleList()
      // 显示当前用户拥有的角色列表
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },

    // 确认按钮
    async btnOK() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    },

    async getDepartment() {
      const result = await getDepartment()
      console.log(result)
      this.depts = transListToTresData(result, 0)
      console.log(this.depts)
      // 初始化获取首个节点 - 根节点（根部门）
      this.queryParams.departmentId = this.depts[0].id
      // 初始化中节点 - 高亮
      // 树形组件的渲染是异步的，必须等到数据渲染成功，在进行选中节点高亮设置。
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },

    // 当前节点切换
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },

    // 员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      console.log('员工数据列表', rows)
      this.list = rows
      this.total = total
    },

    // 底部分页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.queryParams.pagesize = val
      this.getEmployeeList()
    },

    // 防抖处理
    changValue() {
      clearTimeout(this.timer) // 防抖处理
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },

    // excel 导出
    async exportExcel() {
      const result = await exportEmployee()
      console.log(result)
      FileSaver.saveAs(result, '员工表.xlsx')
    },

    // 删除
    // 1.点击确认
    async confirmDel(id) {
      // 删除接口
      await delEmployee(id)
      // 当页最后一个 是就页码减一,重新加载。j
      // 否则重新加载
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.$message.success('删除员工成功')
      this.getEmployeeList()
    }

  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
